/**

返回与给定的前序和后序遍历匹配的任何二叉树。

 pre 和 post 遍历中的值是不同的正整数。

 

示例：

输入：pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
输出：[1,2,3,4,5,6,7]

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。


 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int getIndex(vector<int>& inorder,int key,int l,int r)
    {
        for(int i = l ;  i <= r ; i++ )
        {
            if(inorder[i] == key)
                return i;
        }
        return -1;
    }

    TreeNode* constructFromPrePostHelper(vector<int>& pre, vector<int>& post,int preL,int preR,int postL,int postR)
    {
        if(preL > preR)
            return 0;
        if(preL == preR)
            return new TreeNode(pre[preL]);
        if(pre[preL] != post[postR])
            return 0;
        int index = getIndex(post,pre[preL + 1],postL,postR);
        if(index == -1)
            return 0;
        
        TreeNode * node = new TreeNode(pre[preL]);
        node -> left = constructFromPrePostHelper( pre, post, preL+1, index - postL + preL + 1, postL, index);
        node ->right = constructFromPrePostHelper( pre, post, index - postL + preL + 2, preR, index+1, postR-1);
        return node;
    }
    TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
        if(pre.size() <= 0)
            return 0;
        TreeNode* root = constructFromPrePostHelper(pre,post,0,pre.size()-1,0,post.size()-1);
        return root;
    }
};